package com.snda.sc.auth.simple;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.snda.sc.auth.data.GameHost;
import com.snda.sc.exception.ConfigureException;
import com.snda.sc.utils.CommonUtils;
import com.snda.sc.utils.Constants.Default;

/**
 * 帮助读取SimpleAuth配置（auth.json）。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">李曦</a><br/>
 *         Created at: 2012-10-3 上午9:54:41
 */
public class SimpleAppInfoReader {

	public AppInfo readConfItem(JSONObject config) {
		AppInfo appInfo = new AppInfo();
		appInfo.setAppId(config.getString("appId"));
		appInfo.setAppName(config.getString("appName"));
		appInfo.setCheckUrl(config.getString("checkUrl"));
		appInfo.setBindHps(config.getBoolean("bindHps"));
		appInfo.setAppUrl(config.getString("appUrl"));
		appInfo.setKey(config.getString("key"));
		appInfo.setSecret(config.getString("secret"));
		appInfo.setGameHosts(readGameHost(config.getJSONArray("gameHosts")));
		for (Entry<String, Object> entry : config.entrySet()) {
			appInfo.setProperty(entry.getKey(), entry.getValue());
		}
		return appInfo;
	}

	private Map<String, GameHost> readGameHost(JSONArray gameHostJsons) {
		Map<String, GameHost> hosts = new HashMap<String, GameHost>();
		if (gameHostJsons == null) return hosts;
		for (int i = 0; i < gameHostJsons.size(); i++) {
			JSONObject gameHostJson = gameHostJsons.getJSONObject(i);
			GameHost host = parseGameHost(gameHostJson);
			hosts.put(host.getServerId(), host);
		}
		return hosts;
	}

	private GameHost parseGameHost(JSONObject gameHostJson) {
		GameHost host = new GameHost();

		String serverId = gameHostJson.getString("serverId");
		String url = gameHostJson.getString("url");
		if (!StringUtils.hasLength(serverId) || !StringUtils.hasLength(url)) throw new ConfigureException(
				"GameHost config error, serverId or url is undefined.");

		String appArea = gameHostJson.getString("appArea");
		if (!StringUtils.hasLength(appArea)) {
			if (CommonUtils.isNumber(serverId)) appArea = serverId;
			else appArea = Default.GAMEHOST_APPAREA;
		}

		host.setAppArea(appArea);
		host.setServerId(serverId);
		host.setUrl(url);

		return host;
	}
}
